<template>
    <!-- 试题列表 -->
    <div class="animate__animated" :class="animateClass">
        <div v-if="data?.questionList && data?.questionList.length" class="container">
            <grading-paper-close-button target=".container" />
            <template v-for="(item, index) of data?.questionList">
                <el-card class="card-item">
                    <template #header>
                        <div class="card-item-header">
                            <div class="card-item-header-first">
                                {{ index + 1 }}.{{ item.type }}&nbsp;<span style="color: blue">（&nbsp;{{ item.score }}&nbsp;分&nbsp;）</span>
                            </div>
                            <div>
                                <lemon-tag :value="item.tag" size="small" v-if="item?.tag" />
                                <el-input-number :model-value="getUserScore(item)" @update:model-value="(value:number) => setUserScore(value, item)" :min="0" :max="item.score" size="small" class="card-item-header-input" />
                            </div>
                        </div>
                    </template>
                    <template v-if="item.type === '单选题'">
                        <p class="card-item-title">{{ item.question }}</p>
                        <el-radio-group v-model="item.submitAnswer[0]">
                            <el-radio :value="key" size="large" v-for="(value, key) in item.options" class="card-item-value">
                                <span :style="singleSelectStyle(item, String(key))"> {{ key }}.{{ value }} </span>
                            </el-radio>
                        </el-radio-group>
                        <p>
                            <span v-if="item.submitAnswer[0] === item.answer[0]" style="color: #409eff">正确</span>
                            <span v-else style="color: red">回答错误，正确答案：{{ item.answer[0] }}</span>
                        </p>
                    </template>
                    <template v-else-if="item.type === '多选题'">
                        <p class="card-item-title">{{ item.question }}</p>
                        <el-checkbox-group v-model="item.submitAnswer">
                            <el-checkbox size="large" v-for="(value, key) in item.options" :value="key" class="card-item-value">
                                <span :style="multiSelectStyle(item, String(key))"> {{ key }}.{{ value }} </span>
                            </el-checkbox>
                        </el-checkbox-group>
                        <p>
                            <span v-if="isEqualAnswer(item.submitAnswer, item.answer)" style="color: #409eff">正确</span>
                            <span v-else style="color: red">回答错误，正确答案：{{ item.answer.join("、") }}</span>
                        </p>
                    </template>
                    <template v-else-if="item.type === '判断题'">
                        <p class="card-item-title">{{ item.question }}</p>
                        <el-radio-group v-model="item.submitAnswer[0]">
                            <el-radio :value="key" size="large" v-for="(value, key) in item.options" class="card-item-value">
                                <span :style="judgeStyle(item, String(key))">{{ value }} </span>
                            </el-radio>
                        </el-radio-group>
                        <p>
                            <span v-if="item.submitAnswer[0] === item.answer[0]" style="color: #409eff">正确</span>
                            <span v-else style="color: red">回答错误</span>
                        </p>
                    </template>
                    <template v-else-if="item.type === '填空题'">
                        <paper-question-fill-blank :question="item.question" :answer="item.submitAnswer" :readonly="true" />
                        <p>
                            <span v-if="isEqualAnswer(item.submitAnswer, item.answer)" style="color: #409eff">正确</span>
                            <span v-else style="color: red">回答错误，正确答案：{{ item.answer.join("、") }}</span>
                        </p>
                    </template>
                    <template v-else-if="item.type === '问答题'">
                        <p class="card-item-title">{{ item.question }}</p>
                        <el-input v-model="item.submitAnswer[0]" :autosize="{ minRows: 5, maxRows: 40 }" type="textarea" class="card-item-value" />
                    </template>
                    <template #footer v-if="item.analysis"> <span class="card-footer">解析：</span>{{ item.analysis }} </template>
                </el-card>
            </template>

            <!-- 定义两个按钮 -->
            <div class="footer-btn">
                <el-button type="success" round @click="onSubmit">提交</el-button>
                <!-- <el-button type="info" round @click="onNext" v-if="data.hasNext">下一个</el-button> -->
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { inject, computed, ref, onUnmounted } from "vue";
import { debounce } from "lodash-es";
import { delay } from "@/utils/common";
import GradingPaperCloseButton from "@/views/system/components/gradingPaper/GradingPaperCloseButton.vue";
import PaperQuestionFillBlank from "@/views/system/components/paper/PaperQuestionFillBlank.vue";

//获取自定义全局方法
const { http, emitter } = inject<any>("method");

//父传子
interface Props {
    paperQuestionList?: Record<string, any>;
}
const props = withDefaults(defineProps<Props>(), {
    paperQuestionList: () => ({}),
});

//试题集合
const data = ref<Record<string, any>>(props.paperQuestionList);

//计算单选题的样式
const singleSelectStyle = computed(() => (item: any, key: string) => {
    if (item.submitAnswer[0] === item.answer[0]) {
        return {};
    }
    if (item.submitAnswer[0] === key) {
        return { color: "red" };
    }
    if (item.answer[0] === key) {
        return { color: "#409eff" };
    }
    return {};
});

//计算多选题的样式
const multiSelectStyle = computed(() => (item: any, key: string) => {
    if (isEqual(item.submitAnswer, item.answer)) {
        return {};
    }
    if (item.submitAnswer.includes(key) && !item.answer.includes(key)) {
        return { color: "red" };
    }
    if (!item.submitAnswer.includes(key) && item.answer.includes(key)) {
        return { color: "#409eff" };
    }
    return {};
});

//判断两个数组是否一致
const isEqual = (arr1: string[], arr2: string[]) => {
    if (arr1.length != arr2.length && arr1.length > 0 && arr2.length > 0) return false;
    return arr1.filter((x) => !arr2.includes(x)).length === 0 && arr2.filter((x) => !arr1.includes(x)).length === 0;
};

//计算答案是否一致
const isEqualAnswer = computed(() => (arr1: string[], arr2: string[]) => isEqual(arr1, arr2));

//计算判断题的样式
const judgeStyle = computed(() => (item: any, key: string) => {
    if (item.submitAnswer[0] === item.answer[0]) {
        return {};
    }
    if (item.submitAnswer[0] === key) {
        return { color: "red" };
    }
    if (item.answer[0] === key) {
        return { color: "#409eff" };
    }
    return {};
});

//获取题的得分
const getUserScore = (item: any) => {
    //1.判断题目是否存在得分
    if (item.userScore !== null && item.userScore !== undefined) {
        return item.userScore;
    }
    //2.判断题目提交的答案和答案是否一致
    const userScore = isEqual(item.submitAnswer, item.answer) ? item.score : 0;

    setUserScore(userScore, item);
    return userScore;
};

//设置题的得分
const setUserScore = (value: number, item: any) => {
    data.value?.questionList?.filter((question: any) => question.rowIndex === item.rowIndex)?.forEach((question: any) => (question.userScore = value));
    const totalScore = data.value?.questionList?.reduce((acc: number, cur: any) => acc + cur.userScore, 0) || 0;
    emitter.emit("grading-paper-total-score", totalScore);
};

//提交判分
const onSubmit = debounce(() => {
    let flag = true;
    let param = new Map();
    for (const item of data.value.questionList) {
        if (item.userScore === null || item.userScore === undefined) {
            emitter.emit("message-error", `请为第${item.rowIndex - 1}题打分`);
            flag = false;
            break;
        }
        param.set(item.rowIndex, item.userScore);
    }
    if (flag) {
        doSubmit(param);
    }
}, 200);

//执行阅卷
const doSubmit = (questionScore: Map<number, number>) => {
    //提交判分
    http.post(`gradingPaper/scoring`, { answerId: data.value.answerId, questionScore: Object.fromEntries(questionScore) }).then((res: any) => {
        if (res.success) {
            emitter.emit("message-success", res.data);
            //判断是否有下一个
            if (data.value.hasNext) {
                onNext();
            } else {
                emitter.emit("message-info", "已完成所有题目");
                emitter.emit("grading-paper-table-close");
            }
        } else {
            emitter.emit("message-error", res.message);
        }
    });
};

//动态样式
const animateClass = ref<string>("");

//下一个
const onNext = async () => {
    const ret = await http.get(`/gradingPaper/grading`, { paperId: data.value.paper.id });
    if (ret) {
        animateClass.value = "animate__backOutDown";
        await delay(500);
        animateClass.value = "animate__bounceInDown";
        data.value = ret;
        await delay(1000);
        animateClass.value = "";
    }
};

onUnmounted(() => {
    onSubmit.cancel();
});
</script>

<style lang="less" scoped>
.container {
    width: 100%;
    position: relative;
    .card-item {
        margin-top: 10px;
        .card-item-header {
            display: flex;
            justify-content: space-between;
            .card-item-header-first {
                font-weight: 700;
            }
            .card-item-header-input {
                width: 100px;
            }
        }
        .card-item-title {
            font-weight: 600;
        }
        .card-item-value {
            width: 100%;
            pointer-events: none;
        }
        .card-footer {
            font-weight: 600;
        }
    }

    .footer-btn {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }
}
</style>
